package com.example.gesture.Transformer

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt

@Composable
fun TransformerDemo() {
    //定义方块边长 偏移量 旋转角度 比例等基本信息
    val boxSize = 100.dp
    var offset by remember { mutableStateOf(Offset.Zero) }
    var ratationAngle by remember { mutableStateOf(0f) }
    var scale by remember { mutableStateOf(1f) }
    //利用rememberTransformableState方法获取状态实例 通过回调尾部lamda获取三个状态的信息 进行组件重组
    var transformerState = rememberTransformableState { zoomChange: Float, panChange: Offset, rotationChange: Float ->
        scale *= zoomChange
        offset += panChange
        ratationAngle += rotationChange
    }

    Box(
        modifier = Modifier
            .size(boxSize)
             //注意rotate与offset的调用先后顺序 先旋转再移动
            .rotate(ratationAngle)
            .offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }
            .scale(scale)
            .background(Color.Green)
            .transformable(
                state = transformerState,
                lockRotationOnZoomPan = false
            )
    )
}
